package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.itheima.common.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
     private  UserService userService;
    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request){
        //获取手机号
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);
/*备注:
这里发送短信我们只需要调用封装的工具类中的方法即可，我们这个功能流程跑通，
在测试中我们不用真正的发送短信，只需要将验证码信息，通过日志输出，
登录时，我们直接从控制台就可以看到生成的验证码(实际上也就是发送到我们手机上的验证码)*/
            //需要将生成的验证码保存到Session
            request.getSession().setAttribute(phone,code);
            return R.success("手机验证码发送成功");
        }
        return R.error("短信发送失败");

    }
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpServletRequest request){
        //1获取用户名和密码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        Object codeInSession = request.getSession().getAttribute(phone);
        if (codeInSession!=null&&codeInSession.equals(code)){
            //登录时判断是否为新用户,如果是新用户就自动完成注册
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User one = userService.getOne(lqw);
            if (one==null){
                User user = new User();
              user.setPhone(phone);
              user.setStatus(1);
              userService.save(user);
                request.getSession().setAttribute("user",user.getId());
              return R.success(user);
            }
            //获取ID存入session中,登录成功one
            if (one!=null){
                request.getSession().setAttribute("user",one.getId());
                return R.success(one);
            }

        }
        return R.error("登陆失败");
    }



}
